
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum; 
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class ExportUtil{
	HttpServletResponse response;
	InputStream inputStream;
	ServletOutputStream outputStream;
	String templateName;
	ExcelWriter writer;
	public ExportUtil( HttpServletResponse response , String templateName){
		this.response  = response ;
		this.templateName = templateName;
	}
	public  boolean checkExportData( Result info ) throws IOException{
		if( !ruleInfo.isSuccess()){
			response.setContentType("application/text;charset=utf-8");
			response.getWriter().write( info.getDesc() );
			return false;
		}
		return true;
	}
	public static InputStream getTemplate(String fileName ){
		return ExportUtil.class.getClassLoader()
			.getResourceAsStream("template/" + fileName);
	}
	public  ExcelWriter createWriter( ) throws IOException{
		if( writer!= null )
			return writer;
		this.inputStream = getTemplate( templateName );
		this.outputStream = response.getOutputStream();
		// 设置创建行的方式
		this.writer = EasyExcel.write(outputStream)
			.withTemplate(inputStream)
			.excelType( ExcelTypeEnum.XLSX)
			.build();
		return writer;
	}
	public void write( String fileName ) throws IOException{
		response.setHeader("Content-Disposition", "attachment;filename*=utf-8''"
			+ URLEncoder.encode(fileName, String.valueOf( StandardCharsets.UTF_8)));
		response.setContentType("application/octet-stream");
		//关流
		writer.finish();

	}
	public void close(){
		IOUtils.closeQuietly(inputStream);
		IOUtils.closeQuietly(outputStream);
	}
}